<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <h1 class="info">登录密码</h1>
            </div>
        </template>
        <div class="registerwin">
            <div class="h">请设置新密码</div>
            <el-form :model="form" label-width="120px" ref="ruleFormRef" :rules="rules" :size="formSize" status-icon>
                <div class="registerform">
                    <el-form-item label="用户名" prop="username">
                        <el-input disabled v-model="username" class="input" />
                    </el-form-item>
                    <el-form-item label="原密码" prop="oldPassword" :error="oldPasswordError">
                        <el-input type="password" v-model="form.oldPassword" placeholder="请输入原密码" class="input" @blur="validateOldPassword"/>
                    </el-form-item>
                    <el-form-item label="新密码" prop="password">
                        <el-input type="password" v-model="form.password" placeholder="请输入新密码" class="input" />
                    </el-form-item>
                    <el-form-item label="确认新密码" prop="checkPass">
                        <el-input type="password" v-model="form.checkPass" placeholder="确认新密码" class="input" />
                    </el-form-item>
                    <el-form-item class="button-container">
                        <el-button type="primary" @click="onSave" :disabled="!form.password || !form.checkPass || !form.oldPassword"
                                   style="margin-top: 15px;">保存</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </div>
    </el-card>
</template>

<script setup>
import { ref, reactive } from 'vue'
import $axios from '../components/utils/axios'
import { ElNotification } from 'element-plus'

const form = reactive({
    id: sessionStorage.getItem('id'),
    oldPassword: '',
    password: '',
    checkPass: '',
})

const username = ref('')
username.value = JSON.parse(sessionStorage.getItem('user')).username

const formSize = ref('default')
const ruleFormRef = ref()
const oldPasswordError = ref('')

// 表单 密码双重验证规则
const validatePass2 = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入确认新密码！'))
    } else if (value !== form.password) {
        callback(new Error('确认新密码与新密码不匹配！'))
    } else {
        callback()
    }
}

// 实时验证原密码是否正确
const validateOldPassword = async () => {
    if (form.oldPassword === '') {
        oldPasswordError.value = '请输入原密码';
        return;
    }
    const { data: res } = await $axios.post('/user/validateOldPassword', { id: form.id, oldPassword: form.oldPassword });
    if (res.code === 200) {
        oldPasswordError.value = ''; // 原密码正确，清空错误信息
    } else {
        oldPasswordError.value = '原密码错误，请重新输入';
    }
}

// 表单验证规则
const rules = reactive({
    oldPassword: [
        {
            required: true,
            message: '请输入原密码',
            trigger: 'blur'
        },
    ],
    password: [
        {
            required: true,
            message: '请输入新密码',
            trigger: 'blur'
        },
        {
            min: 5,
            max: 10,
            message: '新密码长度应为5-10个字符',
            trigger: 'blur'
        }
    ],
    checkPass: [
        {
            validator: validatePass2,
            required: true,
            trigger: 'blur'
        }
    ]
})

const onSave = async () => {
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid && !oldPasswordError.value) {
            console.log(form)
            const path = '/user/update'
            const { data: res } = await $axios.post(path, form)
            if (res.code === 200) {
                ElNotification({
                    title: '成功',
                    message: '已成功修改登录密码。',
                    type: 'success',
                })
            } else {
                let message = '未知原因，修改失败！';
                if (res.code === 103) {
                    message = '修改失败，请稍候再试！';
                }
                ElNotification({
                    title: '失败',
                    message,
                    type: 'error',
                })
            }
        } else {
            if (oldPasswordError.value) {
                ElNotification({
                    title: '失败',
                    message: oldPasswordError.value,
                    type: 'error',
                })
            }
            console.log('error submit!', fields)
        }
    })
}
</script>

<style scoped>
.box-card {
    width: 99%;
    height: 95%;
    margin-top: 12px;
    border-radius: 12px;
    background: linear-gradient(to bottom right, #ffebee, #ffcdd2);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 1.5em;
    font-weight: bold;
    color: #d32f2f;
}

.h {
    font-size: 1.25em;
    margin-top: 15px;
    margin-left: 25px;
    font-weight: bold;
    color: #c62828;
    text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
}

.registerform {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.el-form-item {
    margin-bottom: 20px;
    width: 100%;
}

.input {
    width: 250px; /* 缩短输入框长度 */
}

.button-container {
    display: flex;
    justify-content: flex-start;
    gap: 10px;
}

.el-button {
    transition: all 0.3s ease;
}

.el-button:hover {
    transform: translateY(-2px);
}

.info {
    color: #c62828;
    font-weight: bold;
    text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
}
</style>
